#pragma once
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <fstream>
#include "Log.hpp"

namespace wxd
{
    const std::string default_dict_path = "./Dict.txt";
    const std::string sep = ": ";
    class Dict
    {
    public:
        Dict()
            : _path(default_dict_path)
        {
        }

    public:
        // 加载字典文件到容器中
        void Load()
        {
            std::ifstream in(_path);
            if (!in.is_open())
            {
                LOG(LogLevel::FATAL) << "打开文件失败";
                exit(1);
            }
            std::string input;
            while (getline(in, input))
            {
                size_t pos = input.find(sep);
                if (pos == std::string::npos)
                {
                    LOG(LogLevel::WARNING) << "读取" << input << "失败！";
                    continue;
                }
                std::string english = input.substr(0, pos);
                std::string chinese = input.substr(pos + sep.size());
                if (english.empty() || chinese.empty())
                {
                    LOG(LogLevel::WARNING) << "匹配失败！";
                    continue;
                }
                _dict.emplace_back(std::make_pair(english, chinese));
                LOG(LogLevel::INFO) << "加载" << english << " : " << chinese << " 成功";
            }
        }

        size_t Search(const std::string &message)
        {
            for(int i = 0; i < _dict.size();i++)
            {
                if(_dict[i].first == message)
                {
                    return i;
                }
            }
            return npos;
        }

        std::string Translate(const std::string &message)
        {
            //字典类提供翻译功能
            size_t pos = Search(message);
            if(pos == npos)
                return "none";
            else
                return _dict[pos].second;
        }

        

    private:
        std::string _path;                                      // 配置文件的路径+名字
        std::vector<std::pair<std::string, std::string>> _dict; // 存储字典的容器
        static size_t npos;
    };
    size_t Dict::npos = -1;

}